class Node {
  constructor(data) {
    this.data = data
    this.next = null
  }
}
class Nodelist {
  constructor() {
    this.head = null
    this.length = 0
  }
  append(data) {
    //   创建新节点
    const node = new Node(data)
    //   判断是否首节点
    if (this.length === 0) {
      this.head = node
      this.length += 1
    } else {
      let thatNode = this.head
      while (thatNode.next) {
        thatNode = thatNode.next
      }
      thatNode.next = node
      this.length += 1
    }
  }
  get(position) {
    if (position < 0 || position >= this.length) return null
    let thatNode = this.head
    for (let i = 0; i < position; ++i) {
      thatNode = thatNode.next
    }
    return thatNode
  }
  update(position, data) {
    if (position < 0 || position >= this.length) return false
    let thatNode = this.head
    for (let i = 0; i < position; ++i) {
      thatNode = thatNode.next
    }
    thatNode.data = data
    return true
  }
  removeAt(position) {
    if (position < 0 || position >= this.length) return false
    if (position === 0) {
      this.head = this.head.next
      this.length -= 1
      return true
    } else {
      let thatNode = this.head
      for (let i = 0; i < position - 1; ++i) {
        thatNode = thatNode.next
      }
      thatNode.next = thatNode.next.next
      this.length -= 1
      return true
    }
  }
  remove(data) {
    return this.removeAt(this.indexOf(data))
  }
  indexOf(data) {
    let thatNode = this.head
    for (let i = 0; i < this.length; ++i) {
      if (data === thatNode.data) {
        return i
      } else {
        thatNode = thatNode.next
      }
    }
    return -1
  }
  insert(position, data) {
    if (position < 0 || position > this.length) return false
    const node = new Node(data)
    this.length += 1
    if (position === 0) {
      node.next = this.head
      this.head = node
    } else {
      let thatNode = this.head
      // 拿到前一个节点
      for (let i = 0; i < position - 1; ++i) {
        thatNode = thatNode.next
      }
      node.next = thatNode.next
      thatNode.next = node
    }
    return true
  }
  size() {
    return this.length
  }
  isEmpty() {
    return this.length === 0
  }
  toString() {
    let str = ''
    let thatNode = this.head
    while (thatNode) {
      str += ` ${thatNode.data}`
      thatNode = thatNode.next
    }
    return str
  }
}
const nodeList = new Nodelist()
nodeList.append('aaa')
nodeList.append('bbb')
nodeList.append('ccc')
nodeList.remove('ccc')
console.log(nodeList)
